import groovy.sql.Sql

def config = new ConfigSlurper().parse(new File('Configuration.groovy').toURL())

dbuser = config.doc4.database.user
dbpasswd = config.doc4.database.password
dbname = config.doc4.database.name

log = new File(config.doc4.extraction.logfile)
extractiondir = config.doc4.extraction.outputdir

removeFailedExtractions()

def void removeFailedExtractions() {
    def sql = Sql.newInstance("jdbc:mysql://localhost:3306/$dbname", dbuser, dbpasswd, "com.mysql.jdbc.Driver")
    sql.eachRow("select package as pkg from PACKAGE_QUEUE where state='skipped' and action='extraction' order by pkg") {
       row -> 
            pkg = row.pkg;
            
       int i = stringToInteger(pkg);
       pkgFolder = new File(extractiondir+"/$i/"+pkg)
       if (pkgFolder.exists()) {
           command = "rm -fr "+pkgFolder.getAbsolutePath()
           process = command.execute()
           process.waitFor()
           println pkgFolder.getAbsolutePath()+": "+process.exitValue() + " stderror: "+process.err.text+" stdout: "+process.in.text
       }
    }
            
}

def void listFiles(String basedir, String prefix) {
 File base = new File(basedir)
 files = base.listFiles()
 set = new TreeSet()
 for (file in files)
    set.add(file.getName())
 for (file in set) 
    println prefix+file

}

def void removeFilesFromList(String listPath, String folderPath) {
    File list = new File(listPath)
    content = list.text
    files = content.split()
    for (file in files) {
        idx = file.lastIndexOf("/")
        file = file.substring(idx+1)
        toremove = new File(folderPath+"/"+file)
        println toremove
        command = "rm -fr $toremove"
        proc = command.execute()
        proc.waitFor()
        exitcode = proc.exitValue()
        println "return code: $exitcode"
        //println "stderr: ${proc.err.text}"
        //println "stdout: ${proc.in.text}"
    }

}

def int stringToInteger(String str) {
    
    //floor(length(package)/ASCII(package)*1000)
    length = str.length()
    code = (int)str.substring(0,1)
    value = Math.floor(length/code * 1000)
    return value

}
